namespace SampleMiddleware;

public class ApplicationBuild
{
    /// <summary>
    /// 
    /// </summary>
    private List<Func<SampleMiddleware.RequestDelegate, SampleMiddleware.RequestDelegate>> RequestDelegates
    {
        get;
        set;
    }

    public ApplicationBuild()
    {
        RequestDelegates = new();
    }

    /// <summary>
    /// 添加一个 委托
    /// </summary>
    /// <param name="middlewareType"></param>
    public void Use(Func<SampleMiddleware.RequestDelegate, SampleMiddleware.RequestDelegate> next)
    {
        RequestDelegates.Add(next);
    }

    /// <summary>
    /// 创建一个新对象
    /// </summary>
    /// <returns></returns>
    internal ApplicationBuild New()
    {
        return new();
    }
    /// <summary>
    /// 构建
    /// </summary>
    /// <returns></returns>
    public SampleMiddleware.RequestDelegate Build()
    {
        //初始化第一个中间件
        SampleMiddleware.RequestDelegate requestDelegate = (context) => { return Task.CompletedTask; };
        //倒序 这样传递的next 就是下一个中间件委托
        for (int i = RequestDelegates.Count-1; i >=0; i--)
        {
            requestDelegate = RequestDelegates[i].Invoke(requestDelegate);
        }
        return requestDelegate;
    }
}